package utils

import (
	"fmt"
	"image/color"
	"log"
	"os"
	"os/exec"
	"runtime"
	"strings"

	"github.com/atotto/clipboard"
	"github.com/flopp/go-findfont"
)

// 中文乱码问题
func InitsChinese() {
	//设置中文字体:解决中文乱码问题
	fontPaths := findfont.List()
	for _, path := range fontPaths {
		if strings.Contains(path, "msyh.ttf") || strings.Contains(path, "simhei.ttf") || strings.Contains(path, "simsun.ttc") || strings.Contains(path, "simkai.ttf") {
			os.Setenv("FYNE_FONT", path)
			break
		}
	}
}

// 获取当前工作目录
func GetCurrentPath() string {
	// 获取当前工作目录
	currentDir, errs := os.Getwd()
	if errs != nil {
		log.Fatal(errs)
	}
	return currentDir
}

// 复制
func CopyText(value string) {
	// 复制内容到剪切板
	clipboard.WriteAll(strings.TrimSpace(value))

	/* // 读取剪切板中的内容到字符串
	content, err := clipboard.ReadAll()
	if err != nil {
		panic(err)
	} */
}

// 安全截取字符串（按 Unicode 字符数）
func Substring(s string, start, length int) string {
	runes := []rune(s)
	end := start + length
	if end > len(runes) {
		end = len(runes)
	}
	if len(s) > end {
		return string(runes[start:end]) + " ..."
	}
	return string(runes[start:end])
}

// 将十六进制颜色值(如#FFFFFF)转换为Fyne的color.NRGBA
func HexToNRGBA(hex string) color.NRGBA {
	hex = strings.TrimPrefix(hex, "#")
	var r, g, b, a uint8 = 255, 255, 255, 255 // 默认白色完全不透明

	switch len(hex) {
	case 3: // 简写格式 #RGB
		_, err := fmt.Sscanf(hex, "%1x%1x%1x", &r, &g, &b)
		if err != nil {
			return color.NRGBA{}
		}
		r |= r << 4
		g |= g << 4
		b |= b << 4
	case 6: // 标准格式 #RRGGBB
		_, err := fmt.Sscanf(hex, "%02x%02x%02x", &r, &g, &b)
		if err != nil {
			return color.NRGBA{}
		}
	case 8: // 带透明度 #RRGGBBAA
		_, err := fmt.Sscanf(hex, "%02x%02x%02x%02x", &r, &g, &b, &a)
		if err != nil {
			return color.NRGBA{}
		}
	default:
		fmt.Errorf("invalid hex color format")
		return color.NRGBA{}
	}

	return color.NRGBA{R: r, G: g, B: b, A: a}
}

// 跨平台打开浏览器
func OpenBrowser(url string) error {
	var cmd string
	var args []string

	switch runtime.GOOS {
	case "windows":
		cmd = "cmd"
		args = []string{"/c", "start"}
	case "darwin":
		cmd = "open"
	default: // "linux", "freebsd", "openbsd", "netbsd"
		cmd = "xdg-open"
	}
	args = append(args, url)
	return exec.Command(cmd, args...).Start()
}
